angular.module('orders', []).controller('ordersCtrl', [
    '$scope',
    'httpService',
    '$rootScope',
    'alertmsg',
    '$state',
    'confirmservice',
    '$location',
    '$localStorage',
    function($scope, httpService, $rootScope, alertmsg, $state, confirmservice, $location, $localStorage) {
        $scope.nowToken = $localStorage.mutian_token;
        $scope.goMap = function(role, id) {
            if (role == 2) {
                $state.go('service-maporders', {id: id});
            }
        };

        $scope.statesArrs = [
          {
              name: '新订单',
              state: 'new'
          }, {
              name: '预约测量',
              state: 'appointed_measurement'
          }, {
              name: '已测量',
              state: 'measured'
          }, {
              name: '预约安装',
              state: 'appointed_installation'
          }, {
              name: '已安装',
              state: 'installed'
          }, {
              name: '待确认',
              state: 'confirm_installed'
          }, {
              name: '已完成',
              state: 'completed'
          }
        ]
        $scope.searchData = {
            histroy: null,
            q: '',
            start_time: null,
            end_time: null,
            limit: limit,
            state: null
        };
        // 设置是否是历史订单
        $scope.ishistory = false;
        $scope.setType = function(bool) {
            $scope.ishistory = bool;
            $scope.isSearch = false;
            $location.search({params: null});
        };

        $scope.readyorder = {};
        var opts = {
            minDate: new Date(),
            enableTime: true,
            dateFormat: 'Y-m-d H:i',
            mode: 'single',
            locale: 'zh',
            onChange: function(selectedDates, dateStr, instance) {
                var selectTime = new Date(selectedDates[0]).getTime() / 1000;
                var typetime = 'booking_date';
                if ($scope.readyorder.mount_order) {
                    delete $scope.readyorder[typetime]
                    typetime = 'install_date';
                } else {
                    delete $scope.readyorder['install_date']
                }
                $scope.readyorder[typetime] = selectTime;
            }
        };
        $.getScript('./lib/flatpickr/dist/l10n/zh.js', function() {
            flatpickr(".orderflatpickr", opts);
        });

        // 获取我的订单
        // new: 新订单,
        // appointed_measurement: 预约测量,
        // measured: 已测量,
        // appointed_installation: 预约安装,
        // installed: 已安装,
        // complete: 已完成
        var pagenum = 1;
        if ($location.search() && $location.search().page) {
            pagenum = $location.search().page
        }

        $scope.getOrders = function(page, type) {
            $scope.iskeyword = false;
            $scope.keyword = null;
            if (page) {
                pagenum = page;
            }

            if ($scope.ishistory) {
                type = 'history';
            }
            if ($rootScope.mobile) {
                type = 'all';
            }
            $scope.daoDate={
            		url:"web/orders",
            		limit:$scope.searchData.limit,
            		type:type
            }
            if(type==null || type==undefined){
            	 	delete $scope.daoDate.type;
            }
            console.log(limit,type)
            httpService.query("web/orders", {
                page: pagenum,
                limit: limit,
                type: type
            }).then(function(res) {
                if (res.code == 200) {
                    $scope.orders = res.orders;
                    $scope.searchData.limit = res.page.total_count || 10000;
                    $scope.daoDate.limit=res.page.total_count || 10000;
                    console.log($scope.searchData.limit);
                    $scope.page = res.page;
                }
            })
        };
        $scope.isSearch = false;
        $scope.updateUrlPage = function(page) {
            $location.search({page: page})
            if ($scope.isSearch) {
              $scope.searchOrder(page)
            } else {
              $scope.getOrders(page)
            }

        };

        // 预修改订单
        $scope.readyOrder = function(order, index) {
            order.index = index;
            // $scope.readyorder = angular.copy(order);
            $scope.readyorder = {
                id: order.id,
                install_date: order.install_date,
                booking_date: order.booking_date,
                name: order.name,
                tel: order.tel,
                index: index
            };
            $scope.readyorder.tel = parseInt($scope.readyorder.tel);
            // document.getElementById('myordermodal').click();
            if (order.mount_order) {
                opts.defaultDate = $scope.readyorder.install_date * 1000;
            } else {
                opts.defaultDate = $scope.readyorder.booking_date * 1000;
            }
            flatpickr(".orderflatpickr", opts);

        };

        // 服务商修改订单
        $scope.changeOrder = function(order) {
            $state.go('mine.changeorder', {id: order.id});
        };

        // 修改订单
        $scope.ismodalorderform = false;
        $scope.putOrder = function(bool, order) {
            if (!bool) {
                var obj = {}
                httpService.query('web/orders/' + order.id, $scope.readyorder, 'put').then(function(res) {
                    if (res.code == 200) {
                        $scope.orders.splice(order.index, 1, res.order);
                        $('#myModal').modal('hide');
                    } else {
                        alertmsg(res.msg);
                    }
                });
            } else {
                $scope.ismodalorderform = true;
            }

        };

        // $scope.closeModal = function() {
        //     $('#myModal').modal('hide');
        // };

        // 取消订单
        $scope.deleteOrder = function(id, index) {
            confirmservice('是否取消？').then(function(bool) {
                if (bool) {
                    httpService.query('web/orders/' + id, '', 'delete').then(function(res) {
                        if (res.code == 200) {
                            $scope.orders.splice(index, 1);
                        } else {
                            alertmsg(res.msg);
                        }
                    });
                }
            });
        };

        // 搜索功能
        // $scope.q 序列号, 或服务商名称, 省市区
        // $scope.appoint 是否查询审核订单
        // $scope.histroy 是否查询历史订单
        // $scope.state 查询订单状态
        // $scope.startTime 时间戳, 到秒
        // $scope.endTime 时间戳, 秒
        // $scope.page 分页
        // $scope.limit 限制分页
        // 开始时间的初始化
        $scope.q,
        $scope.startTime,
        $scope.endTime,
        $scope.histroy,
        $scope.search_state;
        // 切换历史订单和（进行中/待审核）的订单
        $scope.setHistroy = function(bool) {
            $scope.histroy = bool;
            if (!$scope.histroy) {
              $scope.searchData.histroy = bool
            } else {
              $scope.searchData.histroy = null
            }
        };
        var dateOpts = {
            enableTime: true,
            dateFormat: 'Y-m-d H:i',
            mode: 'single',
            locale: 'zh'
        };
        function difDateOpts(isStart) {
            if (isStart) {
                dateOpts.onChange = function(selectedDates, dateStr, instance) {
                    $scope.startTime = new Date(selectedDates[0]).getTime() / 1000;
                    $('.endTime').attr('disabled', false);
                    flatpickr(".endTime", difDateOpts(false));
                }
            } else {
                dateOpts.minDate = $scope.startTime * 1000;
                dateOpts.onChange = function(selectedDates, dateStr, instance) {
                    $scope.endTime = new Date(selectedDates[0]).getTime() / 1000;
                }
            }
            return dateOpts;
        }
        $.getScript('./lib/flatpickr/dist/l10n/zh.js', function() {
            flatpickr(".startTime", difDateOpts(true));
        });
        $scope.searchOrder = function(page, bool) {
            $scope.isSearch = true;
            var state;
            if ($scope.search_state) {
                state = $scope.search_state.state
            } else {
                state = null
            }
            console.log($scope.q);

            
            $scope.searchData.q = $scope.q || '';
            $scope.searchData.start_time = $scope.startTime;
            $scope.searchData.end_time = $scope.endTime;
            $scope.searchData.state = state;
            $scope.searchData.page = parseInt(page, 10) || 0;

            if (isMobile) {
                $scope.searchData.type = 'all'
            }

            if ($scope.histroy) {
                $scope.searchData.histroy = $scope.histroy;
            }

            if(!!bool) {
                $scope.searchData = $scope.copySearchData;
            }

            httpService.query('web/search_orders', $scope.searchData).then(function(res) {
                if (res.code === 200) {
                    $location.search({params: JSON.stringify($scope.searchData)})
                    $scope.orders = res.orders;
                    $scope.page = res.page;
                    $scope.searchData.limit = res.page.total_count;
                    $scope.searchData.state = $scope.searchData.state;
                } else {
                    alertmsg(res.msg);
                }
            })
            if ($scope.isSearch && !page) {
              $('#search-modal').modal('toggle')
            }
        }

        // 查询订单
        // $scope.iskeyword = false;
        // $scope.getOrdersByKeyWord = function(keyword) {
        //     httpService.query('web/search_orders', { q: keyword, limit: 50 }).then(function(res) {
        //         if(res.code == 200) {
        //             $scope.iskeyword = true;
        //             $scope.orders = res.orders;
        //         } else {
        //             alertmsg(res.msg);
        //         }
        //     })
        // };


        // 切换页面
        $scope.searchPage = 0
        $scope.pageSearch = function() {
            $scope.getOrders(parseInt($scope.searchPage, 10))
        }

        

        if($location.search() && $location.search().params) {
            $scope.copySearchData = JSON.parse($location.search().params);
            $scope.searchOrder(1, true);
        } else {
            $scope.getOrders(pagenum);
        }
    }
]);
